// scripts/publish.js
import path from 'path'
import { globby, globbySync } from 'globby'
import EventEmitter from 'events'
import inquirer from 'inquirer'
import fs from 'fs-extra'
// import shelljs from 'shelljs'
// import { execa, execaCommand, execaCommandSync } from 'execa'
const cwd = process.cwd()

const resolve = _path => path.resolve(cwd, _path);

const packagePaths = globbySync('./src/widget', {
  cwd,
  onlyDirectories: true,
  deep: 1,
})

/*packagePaths.forEach(async item => {
  console.log(resolve(`${item}/config.json`))
  // fs.readFile(resolve(`${item}/settings.tsx`))
  const hasJson = await fs.exists(resolve(`${item}/config.json`)).then((res) => {

  })
  console.log(res)
 /!* fs.readFile(resolve(`${item}/config.json`), 'utf-8').then((res) => {
    if (res) {
      const json = JSON.parse(res);
      const [one, two, three] = json.version.split('.')
      console.log(one, two, three)
    }
  }).catch(error => console.log(error))*!/

  // console.log(import(resolve(item)))
})*/

const choosePackage = async (packages) => {
  return await inquirer.prompt({
    type: 'list',
    name: 'packages',
    message: '选择你要发布的包:',
    choices: [...packages],
  })
}

async function selectedVersion(version) {
  const [ one, two, three ] = version.split('.');
  const choices = {
    type: 'list',
    name: 'packages',
    message: '选择包发布的版本:',
    choices: [
      version,
      `${ one }.${ two }.${ +three + 1 }`,
      `${ one }.${ +two + 1 }.0`,
      `${ +one + 1 }.0.0`,
    ],
  }
  return inquirer.prompt(choices)
}
const widgets = new Map()
packagePaths.forEach(item => {
  const name = item.split('/').pop()
  widgets.set(name, item)
})
const { packages } = await choosePackage(widgets.keys())
const widgetPath = widgets.get(packages)
const hasJson = await fs.exists(resolve(`${widgetPath}/config.json`))
if (hasJson) {
  const file = await fs.readFile(resolve(`${widgetPath}/config.json`), 'utf-8')
  if (file) {
    const json = JSON.parse(file);
    const { packages: newVersion } = await selectedVersion(json.version);

    json.version = newVersion;
    await fs.writeJSON(resolve(`${widgetPath}/config.json`), json, { spaces: 2 });
    console.log(newVersion)
  }
}
console.log('packages: => ', packages, widgets.get(packages), hasJson)
